/**
 * Module dependencies.
 */

var express = require('express');
var http = require('http');
var path = require('path');
var IndexSearcher = require('./indexSearcher');
var IndexBuilder = require('./indexBuilder');

var app = express();

// all environments
app.set('port', process.env.PORT || 4000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);

app.del('/api/json/index/:resourceType/:documentId', function(req, res) {
  var indexBuilder = new IndexBuilder();
  var resourceType = req.params.resourceType;
  var documentId = req.params.documentId;
  if ('null' == documentId) {
    documentId = null;
  }
  indexBuilder.on('error', function(error) {
    res.end(JSON.stringify(error), null, 4);
  }).on('finish', function(data) {
    res.end(JSON.stringify(data), null, 4);
  }).deleteIndex(resourceType, documentId);

});

app.post('/api/json/index/:resourceType', function(req, res) {
  var indexBuilder = new IndexBuilder();
  var userData = req.body;
  var resourceType = req.params.resourceType;
  indexBuilder.on('error', function(error) {
    res.end(JSON.stringify(error), null, 4);
  }).on('finish', function(data) {
    res.end(JSON.stringify(data), null, 4);
  }).buildIndex(resourceType, userData);

});

app.post('/api/json/search/:resourceType', function(req, res) {

  var indexSearcher = new IndexSearcher();
  var resourceType = req.params.resourceType;
  var queryObj = req.body;

  indexSearcher.on('error', function(error) {
    res.end(JSON.stringify(error), null, 4);
  }).on('finish', function(data) {
    res.end(JSON.stringify(data), null, 4);
  }).search(resourceType, queryObj);
});

http.createServer(app).listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

process.on('uncaughtException', function(err) {
  console.error(err);
  console.log("Node NOT Exiting...");
});
